package com.woniu.stafforder.util;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;

import java.math.BigDecimal;

public class AlipayUtil {
    /**
     * 沙箱环境应用appid值
     */
    private static final String APP_ID = "9021000137627513";

    /**
     * java语言需pkcs8私钥，非Java语言使用pkcs1私钥
     */
    private static final String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCyba1sihXi2iSwgOdWU0XkCKW5YQ13GX3RkdLpjsin1XE2XrSipjmsk6JTor4F3FNkxprmJ4AmVwG5F3uMrPAgVZb02JrX2aMj4yhXYyDLM/7kqS0rd3irm6yPuDAX3Ud2ksf5rbGkrTCOlTj2iATqtBDsk4DL+bAbKQbHINrz23KS0qVUOlTWGF+vzACY2pdyu35KUfmzXpg2Qt4fyrmT331a6UMg1ry3cE7r1vtjnSkGVxKclFYa255GlYqczcgVGaQDGuvu23m3O/ffx652WkSsbOQlP4nttLljn+JbnsP1ZftjTEshqvAfVUcaQlfHIj5hOHEUaCiBkZnR8tKpAgMBAAECggEAA7zyfiyiar9BN4Vr004pT66ysiCLZKxfC23vqj74izOYjJgNVr7+xFPPecsWCg9km97hTeMT9zmpapRIXVkeKr9AS17iV5VSqqTOqo4EGN29AFNfA+Mb3xSC1/v23fkfzyciE2QFLbsHImWT7O5KlBQzqpEoiJ1xiBAi+TcB/0vXny6pQNzKqJS4XAC8MNOgWqLyMuApMcTooaVSxobrjRnChN59kUUi4m1CKRbSYUDWhcljeuA+9+L/NFJVseQFtzLH8uyvk6KJTWT0vMdj8S9wOnvpcc485ewC+2RyCGx2zfBiVJ26IiH7yrHQCYrGU1dfRBYmSCPY5VU7Jxw0AQKBgQD1ahe18qY0dKeAFb2sV9cMf08CSmGlJEX1jXyNZu7R/YGe9htsazLQMAnpeC0rtqfZr1W9hb1cW2qFJLkeao1xDl8U1r/DAy7grnCAQVrwjWdqyz+vPuV4i6MVppX5hi9q1o9Ukgb6zDqzRCHplxRmTGlgMFCrGG0cG4o8lV0wKQKBgQC6H+oGxtBwrCNR8vn4OlXr24B3L2rRH2RCuBJ+/YfMu/jh0bDbal5ZIEPLAP99/sU/MD1SDoAeFNgA1YBP0DrR25DELknppzmRZxeD+WPYF61p1faW1x80OFH72vpax+rsh5cFWV7nksJ6QmIHThNOH/nTqgW5QGKF7qzYC6regQKBgQCgcbH6tB7RIIr5hD0y1WK0uu6Oks5vxt0uAkgxsd/kzZXWtROMuDDKRv3T80ukzo/CE408kJkSLnnfffjA1+yMw1aKKzPHbOdS4PiQASpRJkE8YpDKI5amTrRaTUSzk3SgppGiOq3xfV/LH3oEW09s6fvidPPoR9ndjGu92/DGsQKBgA7BsQBQiv4j57j7lq4DkgRdJtZMQB/MaVqQ1YaT+0xUKutcgLUkvc47LKTPs3H93Q2heXskAyxfYrDOPJoXXFJ/If8r3FhWFc5dahPglfXwCqO1fxN+gs7VGErrlaXU699M8MBP0aJylFC1KqiBnC45gskxVbrWS/lqbvHCGw4BAoGBAPHVpDZkMD3bIc/1juGpXbWAOZHGcVf/H9dvFiMRiWnZxQNvxiX6lVST/GAOdrBOB9oZALIhRescEnzvtOVWm0iqsGvSizgp8OfTrtIDLD3wpEOjxqyK+1FxKXTF0OOdY2JaEqLdy3RO+CGoaSR36fWkhsI+nUixtNHz12b/25WS";

    /**
     * 支付宝公钥
     */
    private static final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5NKCLFl7dKiqfcLTqYHdJGdNTHyvniYg5miCTa0Y6p1G3UWpWb3taYC7oi6NdxI0kEe2fulQRRzIUJcqkS/ZUQ8eA5dBZ1WruKOyBXoWsaIWCp8eLeMkoCZxVckQIVrtT0/cvREca7rjL3a17UzrNgFq1zk0pXKrmKUYymvf5RWrO0VYiAlNOJEdeBF3qDvAdYjAL6uZkLcwIkg6Gq9S32yWiPO8CrIXmbnJ04OatHtAvNzI7XSChW7neaFpzJcJZH900qcS1xYlcrWSHRBQrllTtJJHPNDthCzGplGGSfUcYlKSHAFGenbFqvRu5kuFGtdXaJKD5JT7XZSv4APJRwIDAQAB";

    /**
     * 沙箱环境网关地址
     */
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";

    /**
     * 编码格式
     */
    private static final String CHARSET = "utf-8";

    /**
     * 签名方式
     */
    private static final String SIGN_TYPE = "RSA2";

    /**
     * 返回格式
     */
    private static final String FORMAT = "json";
    /**
     * 支付宝异步通知地址
     */
    private static final String NOTIFY_URL = "http://127.0.0.1:8112/alipay/notify";

    /**
     * 支付成功后跳转的地址
     */
    private static final String RETURN_URL = "http://127.0.0.1:8112/alipay/paySuccess";

    /**
     * 根据订单编号和总价，返回二维码
     *
     * @param orderNum
     * @param totalPrice
     * @return 二维码
     * @throws AlipayApiException
     */
    public static String createHtml(String orderNum, BigDecimal totalPrice) throws AlipayApiException {
        AlipayClient alipayClient = getAlipayClient();

        AlipayTradePagePayModel pagePayModel = new AlipayTradePagePayModel();
        // 商品订单编号
        pagePayModel.setOutTradeNo(orderNum);
        // 金额
        pagePayModel.setTotalAmount(totalPrice.toString());
        // 订单标题
        pagePayModel.setSubject(orderNum);
        // 产品码（商家和支付宝签约的产品码）
        pagePayModel.setProductCode("FAST_INSTANT_TRADE_PAY");

        /**
         * 1：订单码-前置模式，对应iframe 宽度不能小于 300px，高度不能小于600px；
         * 3：订单码-迷你前置模式，对应 iframe 宽度不能小于 75px，高度不能小于75px；
         * 4：订单码-可定义宽度的嵌入式二维码，商户可根据需要设定二维码的大小。
         * 跳转模式下，用户的扫码界面是由支付宝生成的，不在商户的域名下。支持传入的枚举值有：
         * 2：订单码-跳转模式
         */
        pagePayModel.setQrPayMode("4");

        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setBizModel(pagePayModel);
        alipayRequest.setReturnUrl(RETURN_URL);
        alipayRequest.setNotifyUrl(NOTIFY_URL);

        // 如果需要返回GET请求，请使用 alipayClient.pageExecute(alipayRequest, "GET")
        AlipayTradePagePayResponse response = alipayClient.pageExecute(alipayRequest, "POST");

        return response.getBody();
    }

    /**
     * 退款
     *
     * @param totalPrice
     * @param orderNum
     * @return
     * @throws AlipayApiException
     */
    public static boolean refund(String orderNum, BigDecimal totalPrice) throws AlipayApiException {
        AlipayClient alipayClient = getAlipayClient();

        AlipayTradeRefundModel refundModel = new AlipayTradeRefundModel();
        // 商品订单编号
        refundModel.setOutTradeNo(orderNum);
        // 需要退款的金额（不能大于订单金额）
        refundModel.setRefundAmount(totalPrice.toString());

        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizModel(refundModel);
        AlipayTradeRefundResponse response = alipayClient.execute(request);

        return response.isSuccess();
    }

    /**
     * 获取Alipay客户端
     *
     * @return
     * @throws AlipayApiException
     */
    private static AlipayClient getAlipayClient() throws AlipayApiException {
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl(GATEWAY_URL);
        alipayConfig.setAppId(APP_ID);
        alipayConfig.setPrivateKey(APP_PRIVATE_KEY);
        alipayConfig.setFormat(FORMAT);
        alipayConfig.setAlipayPublicKey(ALIPAY_PUBLIC_KEY);
        alipayConfig.setCharset(CHARSET);
        alipayConfig.setSignType(SIGN_TYPE);

        //获得初始化的AlipayClient
        return new DefaultAlipayClient(alipayConfig);
    }
}
